import {Component, ViewChild} from '@angular/core';
import {GnJsonFormComponent, GnMessageService, GnModalContent} from "geminis-ng";
import {ActivatedRoute} from "@angular/router";
import {HttpClient} from "@angular/common/http";
import {GnUuidUtils} from "geminis-ng-core";

@Component({
  selector: 'everydata-edit',
  templateUrl: './edit.component.html'
})
@GnModalContent({
  key: 'everydata-edit',
  width: '80vw',
  // height: '75vh',
  top: '40px'
})
export class EditComponent {

  configUrl: string = '';
  private defaultValue: any;
  private collection: string = '';
  private id: string = '';

  @ViewChild(GnJsonFormComponent) form!: GnJsonFormComponent;

  constructor(route: ActivatedRoute,
              private messageService: GnMessageService,
              private http: HttpClient) {
    route.queryParams.subscribe(param => {
      if (param.defaultValue) {
        this.defaultValue = JSON.parse(param.defaultValue);
      }
      this.configUrl = '/api/everydata/forms/' + param.formId;
      this.collection = param.collection;
      this.id = param.id || GnUuidUtils.uuid();
    });

    if (window.parent) {
      window.addEventListener('message', (event: MessageEvent<any>) => {
        const data = event.data;
        switch (data.cmd) {
          case 'submit':
            this.submit().then(() => {
              window.parent.postMessage({
                cmd: 'submitted',
                params: {
                  data: this.form.form.submitValue,
                  businessKey: this.id
                }
              }, '*');
            })
              .catch(error => {
                this.handleError(error);
              });
            break;
        }
      });

      window.setInterval(() => {
        window.parent.postMessage({
          cmd: 'heightChanged',
          params: {
            height: document.documentElement.scrollHeight
          }
        }, '*');
      }, 200);
    }
  }

  configLoaded(): void {
    this.form.form.formGroup.statusChanges.subscribe(() => {
      window.parent.postMessage({
        cmd: 'validChanged',
        params: {
          valid: this.form.form.formGroup.valid
        }
      }, '*');
    });

    this.http.get('/api/everydata/data/' + this.collection + '/' + this.id)
      .subscribe((resp: any): void => {
          if (!resp) {
            resp = {};
          }
          Object.assign(resp, this.defaultValue);
          this.form.form.setValue(resp);
        },
        error => {
          this.handleError(error);
        });
  }

  private submit(): Promise<any> {
    return this.http.put('/api/everydata/data/' + this.collection + '/' + this.id, this.form.form.submitValue)
      .toPromise();
  }

  private handleError(error: any): void {
    window.parent.postMessage({
      cmd: 'error',
      params: {
        error: error.message
      }
    }, '*');
  }
}
